package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.result.Result;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import java.util.UUID;

/**
 * @author atguigu-mqx
 */
@RestController
@RequestMapping("/admin/product")
public class FileUploadController {

    //  使用这个注解的时候，这个类必须在spring 容器中！
    @Value("${minio.endpointUrl}")
    private String endpointUrl;     //  endpointUrl = http://192.168.6.101:9000

    @Value("${minio.accessKey}")
    public String accessKey;

    @Value("${minio.secreKey}")
    public String secreKey;

    @Value("${minio.bucketName}")
    public String bucketName;


    //  /admin/product/fileUpload
    //  参数? springmvc 文件上传！ <bean id = "multiFile" class="">
    //  MultipartFile 对象名 file 是页面传递过来的！
    @PostMapping("fileUpload")
    public Result fileUpload(MultipartFile file){
        String fileName = "";
        try {
            // Create a minioClient with the MinIO server playground, its access key and secret key.
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(endpointUrl)
                            .credentials(accessKey, secreKey)
                            .build();

            // Make 'bucketName' bucket if not exist.
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                // Make a new bucket called 'bucketName'.
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            } else {
                System.out.println("Bucket 'asiatrip' already exists.");
            }

            //  声明一个文件名称：
            fileName = System.currentTimeMillis()+ UUID.randomUUID().toString();
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(
                            file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
        } catch (Exception e) {
            //  异常信息
            e.printStackTrace();
        }

        //  //img14.360buyimg.com/pop/s590x470_jfs/t1/202138/3/18053/73666/61b04c9bE295e6452/45e3c6ee6ff183c5.jpg.webp
        //  http://192.168.200.129:9000/gmall/xxx.jpg;
        String url = endpointUrl+"/"+bucketName+"/"+fileName;
        System.out.println("url:\t"+url);
        //  上传之后的图片url！
        return Result.ok(url);
    }


}